import { Request, Response } from 'express';
import { SocialRelation, User } from '../models';
import { AppError } from '../utils/errorHandler';
import { Op } from 'sequelize';

// 关注用户
export const followUser = async (req: Request, res: Response): Promise<void> => {
    try {
        const { targetId } = req.params;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        if (userId === targetId) {
            throw new AppError('不能关注自己', 400);
        }

        // 检查目标用户是否存在
        const targetUser = await User.findByPk(targetId);
        if (!targetUser) {
            throw new AppError('目标用户不存在', 404);
        }

        // 检查是否已经关注
        const existingRelation = await SocialRelation.findOne({
            where: {
                userId,
                targetId,
                type: 'follow'
            }
        });

        if (existingRelation) {
            throw new AppError('已经关注该用户', 400);
        }

        await SocialRelation.create({
            userId,
            targetId,
            type: 'follow',
            status: 'accepted'
        });

        res.json({ message: '关注成功' });
        return;
    } catch (error) {
        console.error('关注用户失败:', error);
        res.status(500).json({ message: '关注用户失败' });
    }
};

// 取消关注
export const unfollowUser = async (req: Request, res: Response): Promise<void> => {
    try {
        const { targetId } = req.params;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const relation = await SocialRelation.findOne({
            where: {
                userId,
                targetId,
                type: 'follow'
            }
        });

        if (!relation) {
            throw new AppError('未关注该用户', 404);
        }

        await relation.destroy();
        res.json({ message: '取消关注成功' });
        return;
    } catch (error) {
        console.error('取消关注失败:', error);
        res.status(500).json({ message: '取消关注失败' });
    }
};

// 获取粉丝列表
export const getFollowers = async (req: Request, res: Response): Promise<void> => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20 } = req.query;
        const offset = (Number(page) - 1) * Number(limit);
        const followers = await User.findAll({
            include: [{ model: User, as: 'following', where: { id: userId }, attributes: [] }],
            limit: Number(limit), offset, order: [['createdAt', 'DESC']]
        });
        const total = await User.count({ include: [{ model: User, as: 'following', where: { id: userId }, attributes: [] }] });
        res.json({ total, pages: Math.ceil(total / Number(limit)), currentPage: Number(page), followers });
        return;
    } catch (error) {
        console.error('获取粉丝列表失败:', error);
        res.status(500).json({ message: '获取粉丝列表失败' });
    }
};

// 获取关注列表
export const getFollowing = async (req: Request, res: Response): Promise<void> => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20 } = req.query;
        const offset = (Number(page) - 1) * Number(limit);

        const following = await User.findAll({
            include: [{
                model: User,
                as: 'followers',
                where: { id: userId },
                attributes: []
            }],
            limit: Number(limit),
            offset,
            order: [['createdAt', 'DESC']]
        });

        const total = await User.count({
            include: [{
                model: User,
                as: 'followers',
                where: { id: userId },
                attributes: []
            }]
        });

        res.json({
            total,
            pages: Math.ceil(total / Number(limit)),
            currentPage: Number(page),
            following
        });
        return;
    } catch (error) {
        console.error('获取关注列表失败:', error);
        res.status(500).json({ message: '获取关注列表失败' });
    }
};

// 获取好友列表
export const getFriends = async (req: Request, res: Response): Promise<void> => {
    try {
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const friends = await User.findAll({
            include: [{
                model: User,
                as: 'following',
                where: { id: userId },
                attributes: []
            }],
            where: {
                '$following.id$': userId
            }
        });

        res.json(friends);
    } catch (error) {
        console.error('获取好友列表失败:', error);
        res.status(500).json({ message: '获取好友列表失败' });
    }
}; 